<template>
    <section class="mainSection"  style="min-width: 1200px;overflow-x: hidden;">
        <layout :isVertical="true" style="height:100%;">
            <layout layout="center" style="padding:0 15px 0 10px;overflow: hidden;">
                <div style="width:100%;text-align: left;padding-left:10px;font-weight: bold;height:40px;line-height:40px;vertical-align: baseline">
                    <img src="../../imgs/mapIcon.png" />
                    <span style="margin-left:5px;line-height: 10px;vertical-align: bottom;height: 30px;display: inline-block;">影院地图</span>
                    <!-- <div style="float: right">
                        <el-select size="small" @change="provinceChange" v-model="province" placeholder="请选择">
                            <el-option
                                    key="全国"
                                    label="全国"
                                    value="">
                            </el-option>
                            <el-option
                                    key="河北"
                                    label="河北"
                                    value="河北">
                            </el-option>
                            <el-option
                                    key="北京"
                                    label="北京"
                                    value="北京">
                            </el-option>
                        </el-select>
                    </div> -->
                </div>
                <div class="mapEcharts" id="mapEcharts" ref="mapEcharts" :style="{width:mapWidth+'px',height:mapHeight+'px',margin:'auto'}">
                    <h2>加载中...</h2>
                </div>
            </layout>
        </layout>
    </section>
</template>

<script lang="ts">
    import Vue from 'vue'
    import Component from 'vue-class-component'
    import Service from './cinemaMap.service'
    import moment from 'moment';
    import mockData from '@/mock/data/mockData';
    import echarts from 'echarts';
    import "echarts/map/js/china.js";
    import "echarts/extension-src/bmap/bmap.js";
    import "echarts/lib/component/title";
    import "echarts/lib/component/legend";
    
    Component.registerHooks([
        'beforeRouteEnter',
        'beforeRouteLeave',
        'beforeRouteUpdate'
    ]);
    @Component
    export default class cinemaMap extends Vue {
        windowHeight = 700;
        windowWidth = 1800;
        mapWidth = 500;
        mapHeight = 500;
        echartsOption = {};
        // 坐标数据
        geoCoordMap = {
//            '北京影院': [116.46, 39.92],
//            '海门影院': [121.15, 31.89],
//            '鄂尔多斯影院': [109.781327, 39.608266],
//            '招远影院': [120.38, 37.35],
//            '舟山影院': [122.207216, 29.985295],
//            '齐齐哈尔影院': [123.97, 47.33],
//            '盐城影院': [120.13, 33.38],
//            '赤峰影院': [118.87, 42.28],
        };
        // 业务数据
        data = [
//            { name: '北京影院', value: 8 ,errorCount: 3, schedulesErrorCount : 2},
//            { name: '海门影院', value: 8 ,errorCount: 3, schedulesErrorCount : 2 },
//            { name: '鄂尔多斯影院', value: 8 ,errorCount: 3, schedulesErrorCount : 2 },
//            { name: '招远影院', value: 8 ,errorCount: 3, schedulesErrorCount : 2 },
//            { name: '舟山影院', value: 8 },
//            { name: '齐齐哈尔影院', value: 8 },
//            { name: '盐城影院', value: 8 },
//            { name: '赤峰影院', value: 8 },
        ];
        // 初始定位中心点
        mapCenter = [116.46, 35.92];
        // 初始定位的缩放比例
        mapZoom = 5;

        province = '';
        
        constructor() {
            super();
        }

        dateFormat(row, column) {
            var date = row[column.property];
            if (date == undefined) {
                return "";
            }
            return moment(date).format("YYYYMMDD");
        };
        
        getMapData(province){
            // if(province){
            //     this.geoCoordMap = {};
            //     this.data = [];
            //     for(let i=0;i<50;i++) {
            //         let name = '影院xxxx-' + i;
            //         let x = 80 + Math.random() * 40;
            //         let y = 25 + Math.random() * 20;
            //         this.geoCoordMap[name] = [x, y];
            //         if (i < 10) {
            //             this.data.push({
            //                 id: i, name: name, value: i, errorCount: 0, schedulesErrorCount: 0, online: false
            //             })
            //         } else if (i >= 10 && i < 30) {
            //             this.data.push({
            //                 id: i, name: name, value: i, errorCount: 0, schedulesErrorCount: 0, online: true
            //             })
            //         } else if (i >= 30 && i < 40) {
            //             this.data.push({
            //                 id: i, name: name, value: i, errorCount: 3, schedulesErrorCount: 3, online: true
            //             })
            //         } else if (i > 40) {
            //             this.data.push({
            //                 id: i, name: name, value: i, errorCount: 0, schedulesErrorCount: 10, online: true
            //             })
            //         }
            //     }
            //     return;
            // }
            // this.geoCoordMap = {};
            // this.data = [];
            // for(let i=0;i<500;i++) {
            //     let name = '影院xxxx-' + i;
            //     let x = 80 + Math.random() * 40;
            //     let y = 25 + Math.random() * 20;
            //     this.geoCoordMap[name] = [x, y];
            //     if (i < 100) {
            //         this.data.push({
            //             id: i, name: name, value: i, errorCount: 0, schedulesErrorCount: 0, online: false
            //         })
            //     } else if (i >= 100 && i < 300) {
            //         this.data.push({
            //             id: i, name: name, value: i, errorCount: 0, schedulesErrorCount: 0, online: true
            //         })
            //     } else if (i >= 300 && i < 400) {
            //         this.data.push({
            //             id: i, name: name, value: i, errorCount: 3, schedulesErrorCount: 3, online: true
            //         })
            //     } else if (i > 400) {
            //         this.data.push({
            //             id: i, name: name, value: i, errorCount: 0, schedulesErrorCount: 10, online: true
            //         })
            //     }
            // }
            const me = this;
            Service.homeMap().then(res=>{
                //console.log(res)
                let name = '';
                me.data = []
                me.geoCoordMap = res.data.mapData
                if(res.data.data.length>0) {
                    
                    for(let item in res.data.data) {
                        // //console.log(item)
                        // name=item.cinemaNameCn
                        // me.data.push({'name':item.cinemaNameCn,'value':8,'onLine':item.onLine}) 
                        // name=item.cinemaNameCn
                        // me.data.push({'name':item.cinemaNameCn,'value':8,'onLine':item.onLine,cinemaCode:item.cinemaCode}) 
me.data.push({id: item,'name':res.data.data[item].cinemaNameCn,'value':8,'online':res.data.data[item].onLine,cinemaCode:res.data.data[item].cinemaCode,workOrderSum:res.data.data[item].workOrderSum == null?0:res.data.data[item].workOrderSum,tmsScheduleSum:res.data.data[item].tmsScheduleSum== null?0:res.data.data[item].tmsScheduleSum,}) 
                        me.$nextTick(()=>{
                        me.getBaiduMap().then(BMap => {
                            me.showMap()
                        })
                })
                } 
                } else{
                    //  me.getBaiduMap().then(BMap => {
                    //     me.showMap()
                    // })
                }
            })
        }
        
        showMap(){
            let option = this.getOptions(this.data);
            let myChart = echarts.init(this["$refs"]["mapEcharts"]);
            myChart.setOption(option);
        }
        
        getOptions(data) {
            const me = this;
            this.echartsOption = {
                title: {
                    text: '',
                    subtext: '',
                    sublink: '',
                    left: 'center'
                },
                legend: {
                    type: 'scroll',
                    show: true,
                    orient: 'vertical',
                    align: 'left',
                    data: this.getLengend(data),
                    top: 10,
                    left: 10,
                    width: 200,
                    height: 200
                },
                tooltip: {
                    triggerOn: 'mousemove|click',
                    enterable: true,
                    hideDelay: 4000,
                    formatter: function (params) {
                        console.log(params)
                         window.localStorage.setItem('findByPropertyCode',JSON.stringify(params.data))
                        let myChart = echarts.init(me["$refs"]["mapEcharts"]);
                        myChart.on('click',function() {
                            me.$router.push({
                                path:'/watch/cinemaWatchDetail',
                                name:'影厅监控详情',
                            })
                        });
                        let result = '<div style="pointer-events: all;"><span style="font-size:16px;font-weight: bold;margin:10px;">' + params.data.name + '</span><br>';
                        if (params.data.online) {
                            if (params.data.workOrderSum) {
                                result += '有' + params.data.workOrderSum + '个故障<br>';
                                if (params.data.tmsScheduleSum) {
                                    result += '有' + params.data.tmsScheduleSum + '个排期异常';
                                }
                                // result += `<br><input type="button" value="故障监控" onclick="clickEvent(` + params.data.id + `,1)">`;
                                return result;
                            }
                            if (!params.data.workOrderSum && params.data.tmsScheduleSum) {
                                if (params.data.tmsScheduleSum) {
                                    result += '有' + params.data.tmsScheduleSum + '个排期异常';
                                }
                                // result += `<br><input type="button" value="排期监控" onclick="clickEvent(` + params.data.id + `,0)">`;
                                return result;
                            }
                            return result += '影院工作正常';
                        } else {
                            return result += 'TMS系统离线中';
                        }
                    }
                },
                bmap: {
                    center: this.mapCenter,
                    zoom: this.mapZoom,
                    roam: true,
                    /* mapStyle: {
                        styleJson: [{
                            'featureType': 'water',
                            'elementType': 'all',
                            'stylers': {
                                'color': '#d1d1d1'
                            }
                        }, {
                            'featureType': 'land',
                            'elementType': 'all',
                            'stylers': {
                                'color': '#f3f3f3'
                            }
                        }, {
                            'featureType': 'railway',
                            'elementType': 'all',
                            'stylers': {
                                'visibility': 'off'
                            }
                        }, {
                            'featureType': 'highway',
                            'elementType': 'all',
                            'stylers': {
                                'color': '#fdfdfd'
                            }
                        }, {
                            'featureType': 'highway',
                            'elementType': 'labels',
                            'stylers': {
                                'visibility': 'off'
                            }
                        }, {
                            'featureType': 'arterial',
                            'elementType': 'geometry',
                            'stylers': {
                                'color': '#fefefe'
                            }
                        }, {
                            'featureType': 'arterial',
                            'elementType': 'geometry.fill',
                            'stylers': {
                                'color': '#fefefe'
                            }
                        }, {
                            'featureType': 'poi',
                            'elementType': 'all',
                            'stylers': {
                                'visibility': 'off'
                            }
                        }, {
                            'featureType': 'green',
                            'elementType': 'all',
                            'stylers': {
                                'visibility': 'off'
                            }
                        }, {
                            'featureType': 'subway',
                            'elementType': 'all',
                            'stylers': {
                                'visibility': 'off'
                            }
                        }, {
                            'featureType': 'manmade',
                            'elementType': 'all',
                            'stylers': {
                                'color': '#d1d1d1'
                            }
                        }, {
                            'featureType': 'local',
                            'elementType': 'all',
                            'stylers': {
                                'color': '#d1d1d1'
                            }
                        }, {
                            'featureType': 'arterial',
                            'elementType': 'labels',
                            'stylers': {
                                'visibility': 'off'
                            }
                        }, {
                            'featureType': 'boundary',
                            'elementType': 'all',
                            'stylers': {
                                'color': '#fefefe'
                            }
                        }, {
                            'featureType': 'building',
                            'elementType': 'all',
                            'stylers': {
                                'color': '#d1d1d1'
                            }
                        }, {
                            'featureType': 'label',
                            'elementType': 'labels.text.fill',
                            'stylers': {
                                'color': '#999999'
                            }
                        }]
                    }*/
                },
                series: [
                    {
                        name: '工作正常',
                        type: 'effectScatter',
                        coordinateSystem: 'bmap',
                        data: this.convertData(data.sort(function (a, b) {
                            return b.value - a.value;
                        }), 1),
                        symbol: 'rect',
                        symbolSize: function (val) {
                            return 8;
                        },
                        encode: {
                            value: 2
                        },
                        showEffectOn: 'render',
                        rippleEffect: {
                            brushType: 'stroke'
                        },
                        hoverAnimation: true,
                        label: {
                            formatter: '{b}',
                            position: 'right',
                            show: false
                        },
                        itemStyle: {
                            color: 'green',
                            shadowBlur: 10,
                            shadowColor: '#69AFEE'
                        },
                        zlevel: 1,
                    },
                    {
                        name: '离线',
                        type: 'effectScatter',
                        coordinateSystem: 'bmap',
                        data: this.convertData(data.sort(function (a, b) {
                            return b.value - a.value;
                        }), 4),
                        symbol: 'rect',
                        symbolSize: function (val) {
                            return 8;
                        },
                        encode: {
                            value: 2
                        },
                        showEffectOn: 'render',
                        rippleEffect: {
                            brushType: 'stroke'
                        },
                        hoverAnimation: true,
                        label: {
                            formatter: '{b}',
                            position: 'right',
                            show: false
                        },
                        itemStyle: {
                            color: 'gray',
                            shadowBlur: 10,
                           shadowColor: '#69AFEE'
                        },
                        zlevel: 1,
                    },
                    {
                        name: '有故障',
                        type: 'effectScatter',
                        coordinateSystem: 'bmap',
                        data: this.convertData(data.sort(function (a, b) {
                            return b.value - a.value;
                        }), 2),
                        symbol: 'rect',
                        symbolSize: function (val) {
                            return 8;
                        },
                        encode: {
                            value: 2
                        },
                        showEffectOn: 'render',
                        rippleEffect: {
                            brushType: 'stroke'
                        },
                        hoverAnimation: true,
                        label: {
                            formatter: '{b}',
                            position: 'right',
                            show: false
                        },
                        itemStyle: {
                            color: 'red',
                            shadowBlur: 10,
                            shadowColor: '#69AFEE'
                        },
                        zlevel: 1,
                    },
                    {
                        name: '有排期异常',
                        type: 'effectScatter',
                        coordinateSystem: 'bmap',
                        symbol: 'rect',
                        data: this.convertData(data.sort(function (a, b) {
                            return b.value - a.value;
                        }), 3),
                        symbolSize: function (val) {
                            return 8;
                        },
                        encode: {
                            value: 2
                        },
                        showEffectOn: 'render',
                        rippleEffect: {
                            brushType: 'stroke'
                        },
                        hoverAnimation: true,
                        label: {
                            formatter: '{b}',
                            position: 'right',
                            show: false
                        },
                        itemStyle: {
                            color: 'orange',
                            shadowBlur: 10,
                            shadowColor: '#69AFEE'
                        },
                        zlevel: 1,
                    }
                ]
            };
            return this.echartsOption;
        }
        
        clickEvent(id, flag) {
            let params = {
                id: id
            };
            if (flag == 1) {
                this.$router.push({
                    path: '/watch/cinemaWatchDetail',
                    name: '影厅监控详情',
                    params: params
                })
            } else {
                this.$router.push({
                    path: '/watch/schedulesWatch',
                    name: '排期监控详情',
                    params: params
                })
            }
        }
        
        convertData(data, flag){
            var res = [];
            // flag :1 正常
            // flag :2 故障
            // flag :3 排期异常
            // flag :4 离线

            for (var i = 0; i < data.length; i++) {
                // 坐标数据和业务数据的对应,需要唯一key值
                var geoCoord = this.geoCoordMap[data[i].name];
                if (geoCoord) {
                    // 故障优先于排期异常
                    
                    if(flag == 4 && !data[i].online){
                        res.push({
                            id: data[i].id,
                            name: data[i].name,
                            workOrderSum: data[i].workOrderSum,
                            tmsScheduleSum: data[i].tmsScheduleSum,
                            value: geoCoord.concat(data[i].value),
                            online: data[i].online,
                             cinemaCode:data[i].cinemaCode,
                        });
                    }
                    if(data[i].online) {
                        if (flag == 2 && data[i].workOrderSum|| flag == 2&& (data[i].workOrderSum&&data[i].tmsScheduleSum>0)) {
                            res.push({
                                id: data[i].id,
                                name: data[i].name,
                                workOrderSum: data[i].workOrderSum,
                                tmsScheduleSum: data[i].tmsScheduleSum,
                                value: geoCoord.concat(data[i].value),
                                online: data[i].online,
                                 cinemaCode:data[i].cinemaCode,
                            });
                        }
                        if (flag == 3 && data[i].tmsScheduleSum>0 &&data[i].workOrderSum==0) {
                            //console.log(flag,data[i])
                            res.push({
                                id: data[i].id,
                                name: data[i].name,
                                workOrderSum: data[i].workOrderSum,
                                tmsScheduleSum: data[i].tmsScheduleSum,
                                value: geoCoord.concat(data[i].value),
                                online: data[i].online,
                                 cinemaCode:data[i].cinemaCode,
                            });
                        }

                        if (flag == 1 || !flag) {
                            res.push({
                                id: data[i].id,
                                name: data[i].name,
                                workOrderSum: data[i].workOrderSum,
                                tmsScheduleSum: data[i].tmsScheduleSum,
                                value: geoCoord.concat(data[i].value),
                                online: data[i].online,
                                 cinemaCode:data[i].cinemaCode,
                            });
                        }
                    }
                }
            }
            return res;
        }
        
        getLengend(data) {
            let list = [];
//            for (let row of data) {
//                list.push(row.name);
//            }
//            //console.log(list)
            list.push('工作正常');
            list.push('有故障');
            list.push('有排期异常');
            list.push('离线');
            return list;
        }

        // 加载前先通过ak获取百度的地图
        getBaiduMap() {
            return new Promise(function(resolve, reject) {
                window.init = function() {
                    resolve()
                }
                var script = document.createElement('script')
                script.type = 'text/javascript'
                script.src = 'http://api.map.baidu.com/api?v=3.0&ak='+window.process.config.ak+'&callback=init'
                script.onerror = reject
                document.head.appendChild(script)
            })
        }
        
        resizeEvent(){
            this.windowHeight = document.documentElement.clientHeight;
            this.windowWidth = document.documentElement.clientWidth;
            this.mapWidth =  (this.windowWidth - 200);
            this.mapHeight =  (this.windowHeight - 140);
        }

        provinceChange(val){
            // 这里如果需要定位到省的地图,需要重新定位缩放比例和地图中心店
            if(val) {
                this.mapCenter = [116.46, 39.92];
                this.mapZoom = 10;
            }else{
                this.mapCenter = [116.46, 35.92];
                this.mapZoom = 5;
            }
            this.getMapData(val);
            this.showMap();
        }
        
        mounted() {
//            this.getFile();
            const me = this;
           
            me.$nextTick(()=>{
                me.getBaiduMap().then(BMap => {
                    // 需要加定时刷新
                    me.getMapData();
                    me.showMap()
                })
            })
        };

        created() {
            const me = this;
            me.resizeEvent();
            window.clickEvent = this.clickEvent;
            window.onresize = () => {
                return (() => {
                    me.resizeEvent();
                })()
            };
        };
    }
</script>

<style lang="scss" scoped>
    @import '../../styles/home/home.scss';
</style>